/**
 * 嵌套分组排序
 * 准确率: 0.7126%
 */

const FOLDER_OPTIONS = [
  'two',
  'three',
  'four',
  'five',
  'six',
  'seven',
  'eight',
  'ten',
  'twelve',
  'sixteen',
  'twentyfour'
]

function processExerciseGroups(data) {
  // 第一层分组：按 maxConsecutiveIncorrect[最大连续错误次数] 分组并升序排序
  const level1 = Object.entries(
    data.reduce((acc, item) => {
      const key = item.stats.maxConsecutiveIncorrect
      ;(acc[key] = acc[key] || []).push(item)
      return acc
    }, {})
  )
    .sort(([a], [b]) => a - b)
    .map(([key, items]) => ({
      maxConsecutiveIncorrect: Number(key),
      items: processLevel2(items) // 进入第二层处理
    }))

  return level1

  // 第二层处理函数
  function processLevel2(items) {
    return Object.entries(
      items.reduce((acc, item) => {
        // currentConsecutiveIncorrect[当前连续错误次数] - maxConsecutiveIncorrect[最大连续错误次数] 差值分组并升序排序
        const diff = item.stats.currentConsecutiveIncorrect - item.stats.maxConsecutiveIncorrect
        ;(acc[diff] = acc[diff] || []).push(item)
        return acc
      }, {})
    )
      .sort(([a], [b]) => a - b)
      .map(([diffKey, subItems]) => ({
        diff: Number(diffKey),
        subItems: processLevel3(subItems) // 进入第三层处理
      }))
  }

  // 第三层处理函数
  function processLevel3(subItems) {
    return Object.entries(
      subItems.reduce((acc, item) => {
        // currentConsecutiveIncorrect[当前连续错误次数] 分组并降序排序
        const key = item.stats.currentConsecutiveIncorrect
        ;(acc[key] = acc[key] || []).push(item)
        return acc
      }, {})
    )
      .sort(([a], [b]) => b - a) // 当前连续错误降序
      .map(([currentKey, deepItems]) => ({
        currentConsecutiveIncorrect: Number(currentKey),
        deepSubItems: sortFinalLevel(deepItems) // 最终排序
      }))
  }

  // 修改后的最终排序逻辑
  function sortFinalLevel(items) {
    return items.sort((a, b) => {
      // 第一排序条件：准确率升序
      if (a.stats.accuracyRate !== b.stats.accuracyRate) {
        return a.stats.accuracyRate - b.stats.accuracyRate
      }

      // 第二排序条件：按自定义顺序排序 groupType
      const aIndex = FOLDER_OPTIONS.indexOf(a.groupType)
      const bIndex = FOLDER_OPTIONS.indexOf(b.groupType)

      // 处理不在列表中的情况
      if (aIndex === -1 && bIndex === -1) return 0
      if (aIndex === -1) return 1 // 未知类型排最后
      if (bIndex === -1) return -1 // 已知类型优先

      return aIndex - bIndex // 按定义顺序排序
    })
  }
}

function flattenHierarchy(data) {
  const result = []

  // 第一层遍历：maxConsecutiveIncorrect分组
  for (const layer1 of data) {
    if (!layer1.items?.length) continue

    // 第二层遍历：diff分组
    for (const layer2 of layer1.items) {
      if (!layer2.subItems?.length) continue

      // 第三层遍历：currentConsecutiveIncorrect分组
      for (const layer3 of layer2.subItems) {
        if (layer3.deepSubItems?.length) {
          // 收集最终节点
          result.push(...layer3.deepSubItems)
        }
      }
    }
  }

  return result
}

module.exports = (currentGroupArray) => {
  const data = currentGroupArray.filter(
    (item) =>
      item.stats.accuracyRate > 0.8 &&
      item.stats.currentConsecutiveIncorrect > item.stats.avgConsecutiveIncorrect &&
      item.stats.maxConsecutiveIncorrect > item.stats.avgConsecutiveIncorrect
  )

  // console.log('过滤后的数据', data.length)

  const result = processExerciseGroups(data)
  // console.log('处理后的数据', result.length)

  return flattenHierarchy(result)
}
